package com.data;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.util.Log;
import com.bean.AlreadyBookBean;
import com.constant.Constant;
import com.net.ClientError;
import com.net.ClientException;
import com.net.RequestParameter;

/**
 * 
 * @author lenovo
 * 该请求的url连接参数如下：
 * <number>证件号</number>
 * <passwd>密码</passwd>
 * <select>选择</select>参数值值value="cert_no"
 * <returnUrl>返回url</returnUrl>该参数为null
 * 
 * 该函数的功能是登陆图书馆，获取到登陆跳转时的location，并返回已借图书信息列表，传递参数为四个
 * 
 * 使用时注意：在图书馆数据列表中的数据字段值可能为null，使用时候关键数据需要判断一下是否为null
 * 
 */
public final class LoginLibraryData extends BaseData
{
	private final static String TAG = "login_library_data";
	/**
	 * 登陆转发地址
	 */
	private final static String REFERER_URL = "http://202.115.151.118:8080/reader/login.php";
	/**
	 * 登陆连接url
	 */
	private final static String LOGIN_URL = "http://202.115.151.118:8080/reader/redr_verify.php";
	/**
	 * 获取已借图书接口
	 */
	private final static String READER_LIST = "http://202.115.151.118:8080/reader/book_lst.php";
	/**
	 * 请求返回的cookie
	 */
	private String mCookie;
	/**
	 * 已借图书类表
	 */
	private ArrayList<AlreadyBookBean> mAlreadyBook;
	/**
	 * 登陆用户名
	 */
	private String mUserName;
	
	private boolean bRegister = false;
	
	@Override
	public void startParse(RequestParameter parameter) throws Exception
	{
		Log.i(TAG, "开始处理图书馆登陆请求");
		
		// 解析请求数据
		String submitData = encodeParameters(parameter);

		// number=312009070102221&passwd=19900630&select=cert_no&returnUrl=
		String location = login(submitData.replaceFirst("&", ""));
		String stream = null;
		stream = openConnection(location);
		if(stream == null)
			return;

		analyzeUserName(stream);
		analyzeBookList();
		
	}
	
	/**
	 * 登陆时候获取到用户名
	 * @param location ： 重定向url连接
	 * @return ： 返回请求网页数据
	 */
	protected String openConnection(final String location) throws Exception {
		URL url = new URL(location);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
		connection.setRequestProperty("Referer", REFERER_URL);
		connection.setRequestProperty("Host", "202.115.151.118:8080");
		connection.setRequestProperty("Cookie", mCookie);
		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
		connection.setReadTimeout(Constant.SET_READ_TIMEOUT);
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(false);
		
		connection.connect();
		if(connection.getResponseCode() != 200)
		{
			Log.e(TAG, "数据获取失败!");
			throw new ClientException("网络请求失败", ClientError.ERROR_CONNECTION);
		}
		
		return getWebSource(connection.getInputStream(), "utf-8");
	} // openConnection

	/**
	 * 登陆连接 ， 此时的urlS传递的为请求参数，获取到登陆之后的连接重定向地址
	 */
	protected String login(final String urlS) throws Exception
	{
		URL url = new URL(LOGIN_URL);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
		connection.setRequestProperty("Referer", REFERER_URL);
		connection.setRequestProperty("Host", "202.115.151.118:8080");
		//connection.setRequestProperty("Cookie", mCookie);
		//connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		connection.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent"));
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(false);
		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
		connection.setReadTimeout(Constant.SET_READ_TIMEOUT);
		
		OutputStream out = connection.getOutputStream();
		out.write(urlS.getBytes("UTF-8"));
		connection.connect();
		out.close();
		String location = null;
		if(connection.getResponseCode() == 302)
		{
			location = "http://202.115.151.118:8080/reader/" + connection.getHeaderField("Location");
			Log.i(TAG, "获取location成功");
			
			String cookie = connection.getHeaderField("Set-Cookie");
			if(cookie != null)
				mCookie = cookie.split(";")[0];
		}
		else
		{
			Log.e(TAG, "获取登陆图书馆转发地址失败");
			Log.e(TAG, "错误消息号：" + connection.getResponseCode());
			System.out.println(connection.getResponseMessage());
			System.out.println(System.getProperties().getProperty("http.agent"));
			throw new ClientException("网络请求失败", ClientError.ERROR_PASSWD);
		}
		return location;
	} // login
	
	/**
	 * 解析用户名
	 * @param stream
	 */
	protected void analyzeUserName(final String stream) {
		//header_right_font
		
		Document document = Jsoup.parse(stream);
		
		Element header = document.getElementById("header_opac");
		Elements names = header.getElementsByClass("header_right_font");
		header = names.get(1);
		header = header.child(1);
		
		mUserName = header.ownText();
		
		Log.i(TAG, "解析用户名成功");
		
	} // analyzeUserName
	
	/**
	 * 解析当前所借阅图书信息列表
	 */
	protected void analyzeBookList() throws Exception {
		
		URL url = new URL(READER_LIST);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
		connection.setRequestProperty("Referer", REFERER_URL);
		connection.setRequestProperty("Host", "202.115.151.118:8080");
		connection.setRequestProperty("Cookie", mCookie);
		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
		connection.setReadTimeout(Constant.SET_READ_TIMEOUT);
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(false);
		
		connection.connect();
		if(connection.getResponseCode() != 200)
		{
			Log.e(TAG, "数据获取失败!");
			throw new ClientException("网络请求失败", ClientError.ERROR_CONNECTION);
		}
		
		// 解析网页数据
		readStream(getWebSource(connection.getInputStream(), "utf-8"));
		
	} // analyzeBookList
	
	/**
	 * 解析网页数据
	 * @param stream
	 */
	protected void readStream(final String stream) {
		Log.i(TAG, "开始解析所借阅图书列表");
		Document document = Jsoup.parse(stream);
		
		Element mylib = document.getElementById("mylib_content");
		Elements tables = mylib.getElementsByClass("table_line");
		
		// 获取到table中的所有tr标签
		Elements trs = tables.get(0).select("tr");
		
		if(trs.size() > 1)
			mAlreadyBook = new ArrayList<AlreadyBookBean>();
		
		// 跳过第一个标题栏
		for(int i = 1, len = trs.size(); i < len; i++) {
			AlreadyBookBean bean = new AlreadyBookBean();
			Element tr = trs.get(i);
			bean.bar_code = tr.child(0).ownText();
			bean.title = tr.child(1).child(0).ownText();
			bean.url = tr.child(1).child(0).attr("href");
			bean.url = bean.url.replaceFirst("../", "http://202.115.151.118:8080/");
			bean.author = tr.child(1).ownText().replace("/", "");
			bean.borrowDate = tr.child(2).ownText();
			bean.shouldDate = tr.child(3).child(0).ownText();
			bean.renewCount = tr.child(4).ownText();
			bean.collectSite = tr.child(5).ownText();
			bean.attachment = tr.child(6).ownText();
			
			// 获取到续借关键字
			Element div = tr.child(7).child(0).child(0);
			String text = div.attr("onclick");
			String array[] = text.split(",");
			bean.check = array[1].replaceAll("'", "");
			
			mAlreadyBook.add(bean);
		}
		Log.i(TAG, "解析借阅列表数据成功");
	} // readStream

	public String getCookie()
	{
		return this.mCookie;
	}
	
	public String getUserName()
	{
		return this.mUserName;
	}
	
	public ArrayList<AlreadyBookBean> getAlreadyBookList()
	{
		return this.mAlreadyBook;
	}
	
	public boolean getRegister()
	{
		return this.bRegister;
	}
	
	
	public void printData()
	{
		System.out.println("cookie:" + mCookie);
		for(int i = 0; i < mAlreadyBook.size(); i++)
		{
			AlreadyBookBean bean = mAlreadyBook.get(i);
			System.out.println(bean.bar_code);
			System.out.println(bean.author);
			System.out.println(bean.attachment);
			System.out.println(bean.borrowDate);
			System.out.println(bean.collectSite);
			System.out.println(bean.referer);
			System.out.println(bean.renewCount);
			System.out.println(bean.shouldDate);
			System.out.println(bean.title);
			System.out.println(bean.url);
		}
	}
	

}
